package com.example.phoneaddress;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.phoneaddress.util.DBUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity extends AppCompatActivity {

    private EditText etPhone;
    private Button btnSearch;
    private TextView tvResult;
    public static final String TAG="MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //申请权限
        String[]perms={Manifest.permission.READ_CALL_LOG,Manifest.permission.READ_PHONE_STATE};
        if (!EasyPermissions.hasPermissions(this,perms)){
            EasyPermissions.requestPermissions(this,"read call log",2,perms);
        }
        //将数据库文件拷贝到手机内存
        copyDatabase();
        //找到控件
        etPhone = (EditText) findViewById(R.id.et_phone);
        btnSearch = (Button) findViewById(R.id.btn_search);
        Button  btnStartService = (Button) findViewById(R.id.btn_start_service);
        Button  btnStopService  = (Button) findViewById(R.id.btn_stop_service);
        tvResult = (TextView) findViewById(R.id.tv_result);
        //启动和停止服务
        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //启动服务----显示意图
                //参数1-当前Activity，参数2-要启动的服务类
                Intent intent=new Intent(getApplicationContext(),MyService.class);
                startService(intent);
            }
        });

        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //停止
                Intent intent=new Intent(getApplicationContext(),MyService.class);
                stopService(intent);
            }
        });





        //监听来电

        listenIncomingCall();




        //查找
        //点击按钮进行查找
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取输入的电话号码
                String phone=etPhone.getText().toString().trim();
                //查询号码
//                String address=searchAddress(phone);
                String address= DBUtils.searchAddress(getApplicationContext(),phone);
                //显示结果
                tvResult.setText(address);
            }
        });
        //监听文本输入框的变化
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                //改变后，查询号码
                String phone=etPhone.getText().toString().trim();
                //查询号码
                String address=DBUtils.searchAddress(getApplicationContext(),phone);
                //显示结果
                tvResult.setText(address);

            }
        });



    }

    private void listenIncomingCall() {
        //1-获取电话管理者对象
        TelephonyManager tm= (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //让tm对象监听电话状态
        //参数1-监听器对象，参数2-监听内容
        tm.listen(new PhoneStateListener(){
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                //state--电话状态
                // incomingNumber--来电号码
                switch (state){
                    case TelephonyManager.CALL_STATE_IDLE:
                        //空闲状态
                        Log.i(TAG, "空闲状态");
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        //通话状态
                        Log.i(TAG, "通话状态");
                        break;
                    case TelephonyManager.CALL_STATE_RINGING:
                        //响铃状态
                        //获取来电号码

                        Log.i(TAG, "响铃状态"+incomingNumber);

                        //查询归属地
                        String address=DBUtils.searchAddress(getApplicationContext(),incomingNumber);
                        //显示
                        Toast.makeText(getApplicationContext(),address,Toast.LENGTH_LONG).show();
                        break;
                }
            }

        },PhoneStateListener.LISTEN_CALL_STATE);

    }





    private void copyDatabase() {
        //复制，源文件assets/address.db，目标文件当前包下面/data/data/包名/files/address.db
        //第三方资产目录管理者对象，打开文件的输入流
        try {
            //文件输入流关联源文件
            InputStream in=getAssets().open("address.db");
            //输出流关联目标文件
            File file=new File(getFilesDir(),"address.db");
            //判断文件是否存在
            if (!file.exists()){


            FileOutputStream out=new FileOutputStream(file);
            //复制，循环--读源文件写目标文件
            byte[]buf=new byte[1024];
            int len=0;
            while((len=in.read(buf))!=-1){
                out.write(buf,0,len);
                out.flush();
            }
            in.close();
            out.close();
            }else {
                Log.i("MainActivity", "copyDatabase: 已經存在");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
